import { defineStore } from 'pinia'

// 城市选择状态（持久化）
export interface CityState {
  // 当前选中的城市
  currentCity: string
  // 通过定位得到的城市（可能为空）
  locationCity: string
  // 历史访问城市（去重，最多保留10个）
  history: string[]
}

export const useCityStore = defineStore<'city', CityState, {}, {
  setCurrentCity(city: string): void
  setLocationCity(city: string): void
  addHistory(city: string): void
  clearHistory(): void
}>(
  'city',
  {
    state: (): CityState => ({
      // 默认显示“郑州”，避免首次空白
      currentCity: '',
      locationCity: '',
      history: []
    }),
    actions: {
      setCurrentCity(city: string) {
        if (!city) return
        this.currentCity = city
      },
      setLocationCity(city: string) {
        if (!city) return
        this.locationCity = city
      },
      addHistory(city: string) {
        if (!city) return
        const list = this.history.filter(c => c !== city)
        list.unshift(city)
        this.history = list.slice(0, 8)
      },
      clearHistory() {
        this.history = []
      }
    },
    // 使用 pinia-plugin-unistorage 做持久化
    persist: true
  }
)

